package com.partners.component.aop;

import com.partners.configure.wechatmp.WxMpConfiguration;
import com.partners.configure.wechatmp.WxMpProperties;
import com.partners.model.BusinessException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

import static com.partners.constant.ErrorMessageEnum.HTTP_BAD_REQUEST;


/**
 * @author liangyongle
 * @date 2018/8/21 0021
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class AuthsAop {

    @Pointcut("@annotation(com.partners.annotation.Auths)")
    public void authVaildService(){}

    @Resource
    private WxMpProperties wxMpProperties;

    @Autowired
    private HttpServletRequest request;

    @Around("authVaildService()")
    public Object doAuthVaildService(ProceedingJoinPoint pjp) throws Throwable{
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (!request.getMethod().equals(RequestMethod.GET.name())) {
            return pjp.proceed();
        }
        try{
            Object fansInfo = WebUtils.getSessionAttribute(request, "openId");
            if (fansInfo != null) {
                //log.info("缓存{}",fansInfo);
                //缓存openid信息
                return pjp.proceed();
            }
            HttpServletResponse response = requestAttributes.getResponse();
            String returnUrl = this.request.getScheme() +"://" + this.request.getServerName()
                + ":" + this.request.getServerPort()
                + this.request.getServletPath();
            if(this.request.getQueryString() != null){
                returnUrl += "?"+this.request.getQueryString();
            }
            String baseUrl = wxMpProperties.getBaseUrl();
            String url = baseUrl+"/mp/userInfo";
            //绑定用户
            log.info("bind:{}",request.getParameter("bind"));
            if(request.getParameter("bind") != null){
                url = baseUrl+"/mp/userInfo?bind="+request.getParameter("bind");
            }
            //绑定客户
            if(request.getParameter("customer_id") != null){
                url = baseUrl+"/mp/userInfo?customer_id="+request.getParameter("customer_id");
            }

            final WxMpService wxService = WxMpConfiguration.getMpServices().get(wxMpProperties.getBaseAppId());
            String redirectUrl = wxService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, URLEncoder.encode(returnUrl));
            //2.跳转
            response.sendRedirect(redirectUrl);
            return null;

        }catch (Throwable throwable){
          throwable.printStackTrace();
//           return null;
            throw BusinessException.of(HTTP_BAD_REQUEST);
        }
    }

  /*  @After("tokenVaildService()")
    public void doAfter() throws Throwable{
        System.out.println("验证之后");
    }*/
}
